package com.zsh.wanandroid.ui.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.dxq.basic_ui_library.loadSirCallBack.EmptyCallback;
import com.dxq.basic_ui_library.loadSirCallBack.ErrorCallback;
import com.dxq.basic_ui_library.loadSirCallBack.LoadingCallback;
import com.dxq.basic_ui_library.manager.RecyclerViewLinearLayoutManager;
import com.zsh.wanandroid.R;
import com.zsh.wanandroid.api.ApiService;
import com.zsh.wanandroid.base.BaseActivity;
import com.zsh.wanandroid.base.BaseFragment;
import com.zsh.wanandroid.bean.ArticleTags;
import com.zsh.wanandroid.bean.BannerBean;
import com.zsh.wanandroid.bean.BaseResult;
import com.zsh.wanandroid.bean.ArticleBean;
import com.zsh.wanandroid.bean.PageResult;
import com.zsh.wanandroid.http.ApiRequest;
import com.zsh.wanandroid.ui.activity.ArticleActivity;
import com.zsh.wanandroid.ui.adapter.HomeAdapter;
import com.zsh.wanandroid.utils.LogUtils;
import com.zsh.wanandroid.utils.UIUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import cn.bingoogolapple.bgabanner.BGABanner;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * @author zsh
 * @date 2020/3/12.
 * 功能：主页fragment
 */

public class HomeFragment extends BaseFragment {

    private SwipeRefreshLayout swipeRefreshLayout;
    private RecyclerView recyclerView;
    private View headerView;
    private BGABanner banner;

    private HomeAdapter homeAdapter;

    private final static int DEFAULT_PAGE = 0;//默认加载第0页
    private int currentPage = DEFAULT_PAGE;//当前页数
    private int pageCount;//总页数
    private List<ArticleBean<ArticleTags>> articleBeanList = new ArrayList<>();

    //创建HomeFragment
    public static HomeFragment newInstance(Bundle bundle) {
        HomeFragment fragment = new HomeFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle arguments = getArguments();
        if (null != arguments) {

        }
    }

    @Override
    protected int onCreateFragmentView() {
        return R.layout.fragment_common;
    }

    @Override
    protected void initView(View view) {
        swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipeRefreshLayout);
        recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
        recyclerView.addItemDecoration(new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL));
        recyclerView.setLayoutManager(new RecyclerViewLinearLayoutManager(getContext()));
        homeAdapter = new HomeAdapter(R.layout.content_item);
        recyclerView.setAdapter(homeAdapter);
        //添加头部
        headerView = UIUtils.getView(R.layout.home_head_view);
        homeAdapter.addHeaderView(headerView);
        banner = (BGABanner) headerView.findViewById(R.id.banner);
        initUpDownRefreshEvent();

        //item点击事件
        homeAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                List<ArticleBean<ArticleTags>> data = adapter.getData();
                Bundle bundle = new Bundle();
                bundle.putSerializable("data", (Serializable) data.get(position));
                BaseActivity activity = (BaseActivity) getActivity();
                activity.startActivity(ArticleActivity.class, bundle);
            }
        });
    }

    private void initUpDownRefreshEvent() {
        //下拉刷新
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                currentPage = DEFAULT_PAGE;
                loadNet();
            }
        });

        //上拉加载更多
        homeAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                loadNet();
            }
        });
    }

    /**
     * banner初始化
     * @param bannerBeanList
     */
    private void initBanner(final List<BannerBean> bannerBeanList) {
        //是否自动轮播
        banner.setAutoPlayAble(true);
        //设置Banner的布局，图片和文字
        List<String> imagePathList = new ArrayList<>();
        List<String> titleList = new ArrayList<>();
        for (BannerBean bean : bannerBeanList) {
            imagePathList.add(bean.getImagePath());
            titleList.add(bean.getTitle());
        }
        banner.setData(imagePathList, titleList);
        //设置Banner的点击事件
        banner.setDelegate(new BGABanner.Delegate() {
            @Override
            public void onBannerItemClick(BGABanner banner, View itemView, @Nullable Object model, int position) {
                BannerBean bannerBean = bannerBeanList.get(position);
                ArticleBean<ArticleTags> articleTagsArticleBean = new ArticleBean<ArticleTags>();
                Bundle bundle = new Bundle();
                articleTagsArticleBean.setTitle(bannerBean.getTitle());
                articleTagsArticleBean.setLink(bannerBean.getUrl());
                bundle.putSerializable("data", (Serializable) articleTagsArticleBean);
                BaseActivity activity = (BaseActivity) getActivity();
                activity.startActivity(ArticleActivity.class, bundle);
            }
        });
        //设置adapter
        banner.setAdapter(new BGABanner.Adapter() {
            @Override
            public void fillBannerItem(BGABanner banner, View itemView, @Nullable Object model, int position) {
                Glide.with(getContext())
                        .load(model)
                        .placeholder(R.drawable.default_pic)
                        .error(R.drawable.default_pic)
                        .centerCrop()
                        .dontAnimate()
                        .into((ImageView) itemView);
            }
        });
    }


    /**
     * 文章列表
     * @param articleBeanList
     */
    private void initArticle(List<ArticleBean<ArticleTags>> articleBeanList) {

        homeAdapter.replaceData(articleBeanList);
    }

    /**
     * 获取接口数据
     */
    @Override
    protected void loadNet() {
        all();
    }

    @Override
    protected void onNetReload(View v) {
        mBaseLoadService.showCallback(LoadingCallback.class);
        currentPage = DEFAULT_PAGE;
        loadNet();
    }

    private void all() {
        ApiService apiService = ApiRequest.getInstance(getContext()).create(ApiService.class);
        Observable<BaseResult<List<BannerBean>>> banners = apiService.getBanners();
        Observable<BaseResult<List<ArticleBean<ArticleTags>>>> topArticles = apiService.getTopArticles();
        Observable<BaseResult<PageResult<ArticleBean<ArticleTags>>>> articles = apiService.getArticles(currentPage);

        Observable<BaseResult<?>> merge = Observable.merge(banners, topArticles, articles);
        //并行请求
        merge.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BaseResult<?>>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        LogUtils.i("onSubscribe");
                    }

                    @Override
                    public void onNext(@NonNull BaseResult<?> baseResult) {
                        Object o = baseResult.getData();
                        if (o instanceof List) {
                            if (null == o) {
                                mBaseLoadService.showCallback(EmptyCallback.class);
                                return;
                            } else {
                                if (((List) o).get(0) instanceof BannerBean) {
                                    List<BannerBean> bannerBeanList = (List<BannerBean>) o;
                                    LogUtils.i("onNext:1");
                                    if (currentPage == DEFAULT_PAGE)
                                        initBanner(bannerBeanList);
                                } else {
                                    List<ArticleBean<ArticleTags>> articleBeanTopList = (List<ArticleBean<ArticleTags>>) o;
                                    LogUtils.i("onNext:2");
                                    if (currentPage == DEFAULT_PAGE) {
                                        articleBeanList.clear();
                                        articleBeanList.addAll(articleBeanTopList);
                                        //homeAdapter.addData(articleBeanTopList);
                                    }
                                }
                            }
                        } else if (o instanceof PageResult) {
                            currentPage = ((PageResult) o).getCurPage();//当前页
                            pageCount = ((PageResult) o).getPageCount();//总页数
                            List<ArticleBean<ArticleTags>> datas = ((PageResult) o).getDatas();
                            if (null == datas) {
                                mBaseLoadService.showCallback(EmptyCallback.class);
                                return;
                            }
                            LogUtils.i("onNext:3");
                            if (currentPage == (DEFAULT_PAGE + 1)) {
                                articleBeanList.addAll(datas);
                                homeAdapter.replaceData(articleBeanList);
                            } else {
                                homeAdapter.addData(datas);
                            }
                            //initArticle(articleBeanList);
                            if (currentPage < pageCount) {
                                homeAdapter.loadMoreComplete();//加载完成（注意不是加载结束，而是本次数据加载结束并且还有下页数据）
                            } else {
                                homeAdapter.loadMoreEnd();//加载结束
                            }
                        }

                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        LogUtils.i("onError:"+e.getMessage());
                        mBaseLoadService.showCallback(ErrorCallback.class);
                        swipeRefreshLayout.setRefreshing(false);
                    }

                    @Override
                    public void onComplete() {
                        LogUtils.i("onComplete");
                        mBaseLoadService.showSuccess();
                        swipeRefreshLayout.setRefreshing(false);
                    }
                });
    }
}
